package com.wiken.userservice.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wiken.servicecommon.common.Code;
import com.wiken.servicecommon.common.TokenUtil;
import com.wiken.servicecommon.common.exception.DefaultException;
import com.wiken.userservice.entity.User;
import com.wiken.userservice.mapper.UserMapper;
import com.wiken.userservice.service.IUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author wiken
 * @since 2022-12-28
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {

    @Override
    public boolean register(User user) {

        //查询手机号是否存在，如果存在，提示手机号存在
        User resultUser = baseMapper.selectOne(new QueryWrapper<User>().eq("phone_number", user.getPhoneNumber()));

        if(resultUser != null) throw new DefaultException(Code.ERROR, "手机号已存在");

        //为密码进行加密
        BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
        String password = encoder.encode(user.getPassword());

        user.setPassword(password);

        baseMapper.insert(user);
        return true;
    }

    public String login(User user) {
        String token;

        QueryWrapper query = new QueryWrapper<User>();

        BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();

        User userResult = baseMapper.selectOne(new QueryWrapper<User>().eq("phone_number", user.getPhoneNumber()));

        if(userResult == null) throw new DefaultException(Code.ERROR, "用户名或密码错误");

        String hashPassword = userResult.getPassword();
        String password = user.getPassword();

        boolean passwordRight = encoder.matches(password, hashPassword);

        if(!passwordRight) throw new DefaultException(Code.ERROR, "用户名或密码错误");

        Map<String, Object> claims = new HashMap<>();
        claims.put("userId", userResult.getId());
        claims.put("authorities", "user");
        token = TokenUtil.createToken(claims);

        return token;
    }

    @Override
    public Page<User> allUser(Page page) {
        return baseMapper.selectPage(page, null);
    }

    @Override
    public User getUserByUserId(String userId) {
        User user = baseMapper.selectById(userId);
        return user;
    }
}
